package com.tl.ip_location_relation_v4.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import redis.clients.jedis.Jedis;

import com.tl.ip_location_relation_v4.utils.IpUtil;
import com.tl.ip_location_relation_v4.utils.JDBCUtils;
import com.tl.ip_location_relation_v4.utils.RedisCacheUtil;
import com.tl.ip_location_relation_v4.utils.RedisUtil;

public class IpSearchV4 {
	private static String result = null;
	private static RedisUtil redisUtil = RedisUtil.getInstance();
	private static Jedis jedis = redisUtil.getJedis();

	/**
	 * 
	 * @author Antg
	 * @date 2021年7月13日
	 * @param
	 * @return
	 * @Description 查询,redis缓存不设置时长
	 */
	public static String search(String ip) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		long longIp = IpUtil.ipToLong(ip);

		try {
			// 首先先从reids中查询,如果查询到了就不执行sql查询
			// 判断redis是否可用
			if (redisUtil.isOk(jedis)) {
				// 查询
				result = redisUtil.get(ip);
				if (result != null) {
					System.out.println("-->redis查询<--");
					return result;
				}
			}
			conn = JDBCUtils.getConnection();
			st = conn.createStatement();
			String sql = "select location from ip_location_data where "
					+ longIp + ">= start_ip and " + longIp + "<= end_ip";
			rs = st.executeQuery(sql);
			rs.next();
			result = rs.getString("location");
			// 如果查询到了,那么将其加入到缓存中(不设置过期时间)
			if (result != null) {
				// 判断redis是否可用
				System.out.println("-->mysql查询<--");
				if (redisUtil.isOk(jedis)) {
					RedisCacheUtil.cacheToRedisNoLimitTime(jedis, ip, result);
				}
			}

			return result;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			JDBCUtils.release(conn, st);
		}

	}

	/**
	 * 
	 * @author Antg
	 * @date 2021年7月13日
	 * @param
	 * @return
	 * @Description 查询,redis缓存设置时长
	 */
	public static String search(String ip, int limitTime) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		long longIp = IpUtil.ipToLong(ip);

		try {
			// 首先先从reids中查询,如果查询到了就不执行sql查询
			// 判断redis是否可用
			if (redisUtil.isOk(redisUtil.getJedis())) {
				// 查询
				result = redisUtil.get(ip);
				if (result != null) {
					System.out.println("-->redis查询<--");
					return result;
				}
			}
			conn = JDBCUtils.getConnection();
			st = conn.createStatement();
			String sql = "select location from ip_location_data where "
					+ longIp + ">= start_ip and " + longIp + "<= end_ip";
			rs = st.executeQuery(sql);
			rs.next();
			result = rs.getString("location");
			// 如果查询到了,那么将其加入到缓存中(设置过期时间)
			if (result != null) {
				System.out.println("-->mysql查询<--");
				// 判断redis是否可用
				if (redisUtil.isOk(redisUtil.getJedis())) {
					RedisCacheUtil.cacheToRedisLimitTime(jedis, ip, result,
							limitTime);
				}
			}

			return result;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			JDBCUtils.release(conn, st);
		}

	}
}
